A good answer might be:

input 1:input 2:
Rats 12
Enter an integer:
Rats
You entered bad data.
Run the program again.
Good-by
Enter an integer:
12
The square of 12 is 144
Good-by

Syntax of try{} and catch{}

Here is ONE form of the try/catch structure (there are other forms soon to be discussed):

try
{
  // statements, some of which might
  // throw an exception
}

catch ( SomeExceptionType ex )
{
  // statements to handle this
  // type of exception
}


....  // more catch blocks

catch ( AnotherExceptionType ex )
{
  // statements to handle this
  // type of exception
}

// Statements following the structure

Here are a few syntax rules:

  1. The statements in the try{} block can include:
    • Statements that always work.
    • Statements that might throw an exception of one type or another.

  2. There can be one or several catch{} blocks.
    • Also, there can be no catch{} block. This will be discussed in a few pages.

  3. Each catch{} block describes the type of exception it handles.


QUESTION 6:

Is the following code fragment OK?

    try
    {
      // various statements
    }

    catch (NumberFormatException ex )
    {
      // various statements
    }

    catch (IOException ex )
    {
      // various statements
    }

    System.out.println("Good-by" );